<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="showInsert"
        >{{ $t('insert') }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="workOrderList"
      style="width: 100%"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item :label="$t('keyName')">
              <span style="color: #303133 ">{{ props.row.keyName }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        prop="problem"
        :label="$t('problem')"
      />
      <el-table-column
        :formatter="typeFormatter"
        :label="$t('type')"
      />
      <el-table-column
        :label="$t('status')"
      >
        <template slot-scope="scope">
          <el-select v-model="scope.row.status" @change="statusChange(scope.row)">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('time')"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 13px">{{
            formatDate(scope.row.createdDate)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('function')" width="220">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-view"
            @click="see(scope.row)"
          >{{ $t('see') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="gotoChat(scope.row)"
          >{{ $t('history') }}
          </el-button>
          <el-button
            style="color: #f56c6c"
            type="text"
            icon="el-icon-delete"
            @click="del(scope.row)"
          >{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right;margin: 15px 0">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :visible.sync="dialogWorkOrderVisible"
      top="15px"
    >
      <el-form
        label-width="20%"
        :model="workOrder"
      >
        <el-form-item :label="$t('type')">
          <el-select v-model="workOrder.typeId" :disabled="workOrder.workOrderId" @change="typeChange">
            <el-option
              v-for="item in workOrderTypeList"
              :key="item.typeId"
              :label="item.name"
              :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="workOrder.typeId" :label="$t('user')">
          <el-select v-model="workOrder.handleUserId" :disabled="workOrder.workOrderId">
            <el-option
              v-for="item in workOrderTypeUserList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-for="(item ,index) in workOrder.describeList" :key="index" :label="item.name">
          <el-input v-model="item.value" :disabled="workOrder.workOrderId" />
        </el-form-item>
        <el-form-item v-if="workOrder.typeId" :label="$t('problem')">
          <el-input
            v-model="workOrder.problem"
            type="textarea"
            :rows="8"
          />
        </el-form-item>
        <el-form-item v-if="workOrder.workOrderId" :label="$t('enclosure')">
          <div v-for="(item ,index) in workOrder.enclosureList" :key="index" style="position: relative;width: 50%">
            <el-image
              style="width:100%;height: 120px"
              :src="item.downloadPath"
              :preview-src-list="[item.downloadPath]"
              fit="fit"
            />
            <el-button-group style="position: absolute;bottom: 10px;right: 5px">
              <el-button
                type="primary"
                icon="el-icon-download"
                @click="download(item)"
              />
            </el-button-group>
          </div>
        </el-form-item>
        <el-form-item v-else-if="workOrder.typeId" :label="$t('enclosure')">
          <el-upload
            :headers="headers"
            drag
            :action="baseURL+'/erp/work/order/enclosure/uploadAndGet'"
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <i class="el-icon-upload" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogWorkOrderVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addOrUpdate">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { cancelNotice, formatDate, listWorkOrderStatus, successNotice } from '@/util/common'
import {
  deleteWorkOrder,
  getWorkOrder,
  insertWorkOrder,
  pageGetWorkOrder,
  updateWorkOrder
} from '@/api/erp/erpWorkOrderApi'
import { getCompanyId, getPageSize, getToken, getUserId, setPageSize } from '@/util/storage'
import { listWorkOrderType } from '@/api/erp/erpWorkOrderTypeApi'
import { listWorkOrderTypeDescribeKey } from '@/api/erp/erpWorkOrderTypeDescribeKeyApi'
import { listWorkOrderTypeUser } from '@/api/erp/erpWorkOrderTypeUserApi'

export default {
  name: 'WorkOrder',
  data() {
    return {
      baseURL: window.VUE_APP_BASE_API,
      headers: {
        'access-token': getToken()
      },
      workOrderList: [],
      workOrder: {
        describeList: [],
        enclosureList: []
      },
      dialogWorkOrderVisible: false,
      currentPage: 0,
      total: 0,
      pageSize: getPageSize(),
      userId: getUserId(),
      companyId: getCompanyId(),
      workOrderTypeList: [],
      workOrderTypeUserList: [],
      statusList: listWorkOrderStatus(this)
    }
  }, created() {
    this.pageGetWorkOrder()
    this.listWorkOrderType()
  },
  methods: {
    download(item) {
      window.open(
        item.downloadPath
      )
    },
    see(item) {
      getWorkOrder({
        workOrderId: item.workOrderId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.workOrder = data
          this.listWorkOrderTypeUser()
          this.dialogWorkOrderVisible = true
        }
      })
    },
    handleSuccess(res, file, fileList) {
      console.log(file)
      const { code, data } = res
      if (code === '200') {
        this.workOrder.enclosureList.push({
          enclosureId: data.enclosureId,
          downloadPath: ''
        })
      }
    },
    handlePictureCardPreview(file) {

    },
    handleError(err, file, fileList) {
      console.error(err)
      console.error(file)
      console.error(fileList)
    },
    typeChange() {
      this.listWorkOrderTypeDescribeKey()
      this.listWorkOrderTypeUser()
    },
    listWorkOrderTypeDescribeKey() {
      listWorkOrderTypeDescribeKey({
        typeId: this.workOrder.typeId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const describeList = []
          for (const item of data) {
            describeList.push({
              keyId: item.keyId,
              name: item.name,
              value: '',
              required: item.required
            })
          }
          this.workOrder.describeList = describeList
        } else {
          this.workOrder.describeList = []
        }
      })
    },
    listWorkOrderTypeUser() {
      listWorkOrderTypeUser({
        typeId: this.workOrder.typeId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.workOrderTypeUserList = data
          this.workOrder.handleUserId = data[0].userId
        } else {
          this.workOrderTypeUserList = []
          this.workOrder.handleUserId = null
        }
      })
    },
    listWorkOrderType() {
      listWorkOrderType({
        companyId: this.companyId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.workOrderTypeList = data
        } else {
          this.workOrderTypeList = []
        }
      })
    },
    typeFormatter(item) {
      for (const type of this.workOrderTypeList) {
        if (type.typeId === item.typeId) {
          return type.name
        }
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetWorkOrder()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageGetWorkOrder()
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    showInsert() {
      this.workOrder = {
        describeList: [],
        enclosureList: [],
        companyId: this.companyId
      }
      this.dialogWorkOrderVisible = true
    },
    pageGetWorkOrder() {
      pageGetWorkOrder({
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        createdUserId: this.userId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.total = data.total
          this.workOrderList = data.data
        } else {
          this.total = 0
          this.workOrderList = []
        }
      })
    },
    statusChange(item) {
      this.workOrder = item
      this.addOrUpdate()
    },
    addOrUpdate() {
      const json = {
        ...this.workOrder
      }
      if (!json.workOrderId) {
        insertWorkOrder(json).then(res => {
          const { code } = res
          if (code === '200') {
            this.dialogWorkOrderVisible = false
          }
          this.pageGetWorkOrder()
        })
      } else {
        updateWorkOrder(json).then(res => {
          const { code } = res
          if (code === '200') {
            this.dialogWorkOrderVisible = false
          }
          this.pageGetWorkOrder()
        })
      }
    },

    gotoChat(item) {
      this.$router.push({
        path: '/erp/workOrder/chat/' + item.workOrderId,
        query: { workOrderId: item.workOrderId }
      })
    },
    del(item) {
      const that = this
      this.$confirm(this.$t('delete'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteWorkOrder({
            workOrderId: item.workOrderId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
            }
            that.pageGetWorkOrder()
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    }
  }
}
</script>

